package com.ermao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ermao.mapper.AccountMapper;
import com.ermao.mapper.CategoryMapper;
import com.ermao.mapper.UserMapper;
import com.ermao.pojo.Account;
import com.ermao.pojo.Category;
import com.ermao.pojo.User;
import com.ermao.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Ermao
 * Date: 2021/9/6 0:16
 */
@Service
public class AccountServiceImpl implements AccountService {

	private AccountMapper accountMapper;
	private CategoryMapper categoryMapper;
	private UserMapper userMapper;

	@Autowired
	public AccountServiceImpl(AccountMapper accountMapper, CategoryMapper categoryMapper, UserMapper userMapper) {
		this.accountMapper = accountMapper;
		this.categoryMapper = categoryMapper;
		this.userMapper = userMapper;
	}

	@Override
	public boolean addAnAccount(Integer userId, Double accountAmount, Integer accountType, Integer categoryId, Date accountTime, String accountComment) {
		User user = userMapper.selectById(userId);
		Category category = categoryMapper.selectById(categoryId);
		if (user == null || category == null) {
			return false;
		}
		Account account = new Account();
		account.setAccountAmount(accountAmount);
		account.setAccountComment(accountComment);
		account.setAccountTime(accountTime);
		account.setAccountType(accountType);
		account.setCategoryId(categoryId);
		account.setUserId(userId);

		return accountMapper.insert(account) > 0;
	}

	@Override
	public Account selectAnAccountByAccountId(Integer accountId) {
		QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("account_id", "account_amount", "account_type", "category_id", "account_time", "account_comment");
		queryWrapper.eq("account_id", accountId);
		return accountMapper.selectOne(queryWrapper);
	}

	@Override
	public boolean deleteAnAccount(Integer accountId) {
		Account account = accountMapper.selectById(accountId);
		if (account == null) {
			return false;
		}
		return accountMapper.deleteById(account) > 0;
	}


	@Override
	public boolean updateAnAccount(Integer accountId, Double accountAmount, Integer accountType,
								   Integer categoryId, Date accountTime, String accountComment) {
		// 查询这笔记录和分类ID是否存在
		Account account = accountMapper.selectById(accountId);
		Category category = categoryMapper.selectById(categoryId);
		if (account == null || category == null) {
			return false;
		}
		// 正式修改
		Account newAccount = new Account();
		newAccount.setAccountId(accountId);
		newAccount.setAccountAmount(accountAmount);
		newAccount.setAccountType(accountType);
		newAccount.setCategoryId(categoryId);
		newAccount.setAccountTime(accountTime);
		newAccount.setAccountComment(accountComment);
		return accountMapper.updateById(newAccount) > 0;
	}
}
